﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Smarly.Ebook.Model;
using Smarly.Web.Controllers.Base;

namespace Smarly.Web.Areas.Admin.Controllers
{
	public class EBookController : AdminBaseController
	{

		public ActionResult Index(string url, bool full = true)
		{
			bool isXml = url.EndsWith(".xml");


			EBookTree model = new EBookTree().Get(UserIdentity, "/"  + (isXml ? url.Remove(url.Length - ".xml".Length) : url), full);

			if (isXml)
			{
				Response.Clear();
				Response.ContentType = "text/xml";

				return Content(RenderPartialViewToString(this, "Index", model), "text/xml"); ;
			}
			else
			{
				return View(model);
				
			}

/*
*/
		}

		public static string RenderPartialViewToString(Controller controller, string viewName, object model)
		{
			controller.ViewData.Model = model;
			try
			{
				using (StringWriter sw = new StringWriter())
				{
					ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
					ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
					viewResult.View.Render(viewContext, sw);

					return sw.GetStringBuilder().ToString();
				}
			}
			catch (Exception ex)
			{
				return ex.ToString();
			}
		}

	}
}
